package com.example.pceb.utils;

import com.example.pceb.entity.User;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.junit.Test;

import javax.crypto.SecretKey;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.UUID;
public class JwtUtil {
    public static String secretKeyStr = "azureazureazureazureazureazureazureazureazureazureazureazureazure";
    public static final SecretKey KEY = Keys.hmacShaKeyFor(secretKeyStr.getBytes());

    /**
     * 生成JWT令牌
     * @param username
     * @param identity
     * @return
     */
    public static String generateToken(String username, String identity){
        String uuid = UUID.randomUUID().toString();
        Date exprireDate = Date.from(Instant.now().plus(7, ChronoUnit.DAYS));
        return Jwts.builder()
                .header()
                .add("typ","JWT")
                .add("alg","HS256")
                .and()
                .claim("username",username)
                .claim("identity",identity)
                .id(uuid)
                .expiration(exprireDate)
                .signWith(KEY,Jwts.SIG.HS256)
                .compact();
    }

    /**
     * 解析token
     */
    public static Claims parseToken(String token){
        return Jwts.parser()
                .verifyWith(KEY)
                .build()
                .parseSignedClaims(token)
                .getPayload();

    }

}
